"""
@filename: schoolapi.py
@project: flask_project
@author: wlf
@time: 2022-09-07
"""
from flask_restful import Resource, Api
from flask import Blueprint, request, session
from model import db
from libs.response import generate_response
from model.school import School
from sqlalchemy import or_

school_bp = Blueprint("schoolapi", __name__, url_prefix="/v1")
api = Api(school_bp)


class SchoolView(Resource):
    def post(self):
        name = request.json.get("school_name")
        introduction = request.json.get("introduction")
        school = School.query.filter(School.school_name.like(name)).all()
        if school is None:
            school_info = School(school_name=name, introduction=introduction)
            db.session.add(school_info)
            db.session.commit()
            return generate_response(message="post user success")
        else:
            return generate_response(status_code=10001, message="The school already exists!!!")

    def get(self, id=None):
        keyword = request.args.get("keyword")
        result_list = []
        if id is not None:
            school_info = School.query.get(id)
            if school_info is not None:
                result_list.append(school_info)
            else:
                return generate_response(status_code=10001, message="school not found")
        else:
            if keyword is not None:
                schools_info = School.query.filter(or_(School.school_name.like('%'+keyword+'%'), School.introduction.like('%'+keyword+'%'))).all()
            else:
                schools_info = School.query.all()
            result_list += schools_info

        return generate_response(message="get user success", data=[school.to_json1() for school in result_list])

    def put(self, id):
        mod_school = School.query.get(id)
        if mod_school:
            # 可以修改什么属性就接收客户端传递的属性过来即可
            school_name = request.json.get("school_name")
            introduction = request.json.get("introduction")

            # 修改实例对应的属性
            mod_school.username = school_name
            mod_school.introduction = introduction

            db.session.add(mod_school)
            db.session.commit()

            return generate_response(message="modify user success")
        else:
            return generate_response(status_code=10001, message="user not found")


api.add_resource(SchoolView, "/school")
api.add_resource(SchoolView, "/school/<int:id>", endpoint="schoolviewapi")
